﻿using AdvancedPoll.Models;
using Orchard.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AdvancedPoll.Services
{
    public class VotingService : IVotingService
    {
        private readonly IRepository<PollRecord> _pollRepository;
        private readonly IRepository<PollVoteRecord> _voteRepository;
        private readonly IRepository<PollResultRecord> _resultRepository;

        public VotingService(IRepository<PollRecord> pollRepository,
            IRepository<PollVoteRecord> voteRepository,
            IRepository<PollResultRecord> resultRepository)
        {
            _pollRepository = pollRepository;
            _voteRepository = voteRepository;
            _resultRepository = resultRepository;
        }

        public bool CanVote(int pollId, string user, string fingerprint)
        {
            if(user == "Anonymous")
                return _voteRepository.Count(v => v.PollPartRecord.Id == pollId && v.Fingerprint == fingerprint) == 0;
            else
                return _voteRepository.Count(v => v.PollPartRecord.Id == pollId && v.Username == user) == 0;
        }

        public void TryVote(int pollId, string user, string fingerprint, IEnumerable<Models.PollChoiceRecord> choices)
        {
            if (choices == null)
                throw new ArgumentNullException("choices");
            PollRecord poll = _pollRepository.Get(pollId);
            foreach (var choice in choices)
            {
                PollVoteRecord vote = new PollVoteRecord
                {
                    Fingerprint = fingerprint,
                    PollChoiceRecord = choice,
                    PollPartRecord = poll,
                    Username = user,
                    VoteDateUtc = DateTime.Now
                };
                _voteRepository.Create(vote);
                var result = _resultRepository.Get(r => r.PollChoiceRecord.Id == choice.Id);
                result.Count++;
                _resultRepository.Update(result);
            }
        }
    }
}